<template>
    <!-- 
        1.dialog的显示与否是通过 :visible.sync的值来控制的
        2.close-on-click-modal="false"控制点击遮罩是否隐藏弹出层；
    -->
    <el-dialog title="编辑Spu" width="560px" :visible.sync="editSpuDialogVisible" :close-on-click-modal="false" :before-close="closeAndReset">
        <!-- rules表示绑定我们自定义的规则 -->
        <el-form :model="editSpu"  ref="editForm">
            <el-form-item label="标题" label-width="70px" prop="title">
                <el-input v-model="editSpu.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="副标题" label-width="70px" prop="subtitle">
                <el-input v-model="editSpu.subtitle" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="价格" label-width="70px" prop="price">
                <el-input v-model="editSpu.price" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="折扣价" label-width="70px" prop="discountPrice">
                <el-input v-model="editSpu.discountPrice" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item  label="分类" label-width="70px" prop="categoryId">
                <el-select v-if="this.editSpu.category" v-model="this.editSpu.category.id"  :disabled=true placeholder="请选择">
                 <el-option              
                :label="editSpu.category.name"
                :key="editSpu.category.id"
                :value="editSpu.category.id"
                >
                </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="是否上架" label-width="70px" prop="online">
            <el-switch v-model="editSpu.online"></el-switch>
            </el-form-item>

            <el-form-item label="主图" label-width="70px" prop="mainImgUrl">
                <el-upload
                    class="avatar-uploader"
                    action=""
                    :show-file-list="false"
                    :http-request="editUploadFile"
                    :on-success="handleMainImgSuccess"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="this.editSpu.mainImgUrl" :src="this.editSpu.mainImgUrl" class="avatar" style="width:90px;height:100px">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>

            <el-form-item label="轮播图" label-width="70px" prop="carouselImageUrls">
              <el-upload
                action=""
                class="avatar-uploader"
                :http-request="editUploadFile"
                list-type="picture-card"
                :file-list="fileList"
                :on-success="handlePictureCardPreview"
                :on-remove="handleRemove"
                :limit='4'>
                <i class="el-icon-plus"></i>
              </el-upload>

              <el-dialog :visible.sync="dialogVisible">             
                    <!-- <img width="100%" :src="this.addSpu.carouselImages" alt="" />    -->
                    <img  width="100%" :src="this.editSpu.carouselImages" style="width:70px;height:70px" />                     
              </el-dialog>
            </el-form-item>

            <el-form-item label="标签" label-width="70px" prop="dynamicTags">
            <el-tag
                :key="tag"
                v-for="tag in this.editSpu.dynamicTags"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)">
                {{tag}}
            </el-tag>
            <el-input
                class="input-new-tag"
                v-if="inputVisible"
                v-model="inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm">
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">新增标签</el-button>
            </el-form-item>

            <el-form-item label="规格" label-width="70px" prop="specKeysIds">
                <el-select v-model="editSpu.specKeysIds" multiple placeholder="请选择" >
                 <el-option
                v-for="item in specKeys"               
                :label="item.id+'#'+item.name"
                :key="item.id"
                :value="item.id">
                </el-option>
                </el-select>
            </el-form-item>
            
            <el-form-item label="描述" label-width="70px" prop="description">
                <el-input v-model="editSpu.description" autocomplete="off"></el-input>
            </el-form-item>
         
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="closeAndReset">取 消</el-button>
            <el-button type="primary" @click="sureEdit">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import http from '@/utils/request.js'
const OSS = require('ali-oss')
    const client= new OSS({
      accessKeyId: 'LTAI5tBRSqJDJyEqimryPDzH',  // 查看你自己的阿里云KEY
      accessKeySecret: 'wP3KENQ5jPYlwSf0vKooIiFmOH9vT4', // 查看自己的阿里云KEYSECRET
      bucket: 'll0803', // 你的 OSS bucket 名称 
      region: 'oss-cn-hangzhou', // bucket 所在地址，我的是 华北2 北京
      // cname: true // 开启自定义域名上传
      // endpoint:"file.xxxx.live" // 自己的域名
    })
export default {
    data() {
        return {
            // editUserDialogVisible是用来控制弹出框是否显示, false表示不显示；true表示显示
            dialogVisible: false,
            editSpuDialogVisible: false,
            editSpu: {
                
            },
            specKeys:[],
            fileList:[],
            //标签属性           
            inputVisible: false,
            inputValue: ''
            
        }
    },
    methods: {
        // 根据id查询，然后回显数据
        getById(id) {
            http.get(`spu/${id}`).then(res => {              
                this.editSpu = res 
                console.log('----');   
                console.log( this.editSpu); 
                this.editSpu.carouselImages.forEach(element => {
                    this.fileList.push({url:element})
                });
                        
            }) 
        },
        getSpecKeys(){
            http.get('spec').then(res => {
            this.specKeys = res
        })
        },
        // 用户确认编辑
        async sureEdit() {
            try {
                // 通过await的方式校验表单的时候，如果校验不通过，this.$refs.editForm.validate()
                // 会抛出异常
                await this.$refs.editForm.validate()
                this.fileList = [] 
                // 代码如果能走下来，表示校验通过
                await http.put(`spu`, this.editSpu)
                // 编辑成功的提示消息
                this.$message({ message: '编辑成功', type: 'success', duration: 1000})
                // 隐藏模态框
                this.editSpuDialogVisible = false
                // 重新查询数据
                this.$emit('refresh')
            }catch(err) {
                console.log(err);
            }
        },
        closeAndReset() {
            this.fileList = [] 
            // 隐藏模态框
            this.editSpuDialogVisible = false
        },
        handleClose(tag) {
        this.editSpu.dynamicTags.splice(this.editSpu.dynamicTags.indexOf(tag), 1);
      },
      
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
       },
       //标签方法 添加
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
            this.editSpu.dynamicTags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
        console.log(this.editSpu.dynamicTags);
      },
        //主图方法
        handleMainImgSuccess(res) {
        this.editSpu.mainImgUrl = res.url
        // console.log(this.addSpu.mainImgUrl);
      },
      beforeAvatarUpload(file) {
        const isJPEG = file.type === 'image/jpeg'
        const isJPG = file.type === 'image/jpg'
        const isPNG = file.type === 'image/png'
        const imgFormat = !isJPG && !isJPEG && !isPNG
        const isLt4M = file.size / 1024 / 1024 < 4 
        if (imgFormat) {
          this.$message.error('上传头像图片只能是JPG或者PNG格式!');
        }
        if (!isLt4M) {
          this.$message.error('上传头像图片大小不能超过 4MB!');
        }
        return !imgFormat && isLt4M
      },
    async editUploadFile (options) {
    try {
        let file = options.file; // 拿到 file
        let fileName = file.name.substr(0,file.name.lastIndexOf('.'))
        let date = new Date().getTime()
        let fileNames = `${date}_${fileName}` // 拼接文件名，保证唯一，这里使用时间戳+原文件名
              // 上传文件,这里是上传到OSS的 uploads文件夹下
        client.put('SPU/' + fileNames, file).then(res=>{
        if (res.res.statusCode === 200) {
        options.onSuccess(res)
        }else {
            options.onError("上传失败")
        }
      })
        }catch (e) {
         options.onError("上传失败")
        }
      },
      //轮播图方法 移除方法
      handleRemove(file) {
        console.log(file.url);
        this.editSpu.carouselImages.pop(file.url);
        this.fileList.pop(file);
        console.log(this.fileList);

        console.log(this.editSpu.carouselImages);
      },
      handlePictureCardPreview(file) {
        // console.log(file.url);
        this.editSpu.carouselImages.push(file.url);
        this.fileList.push({url:file.url})
        console.log(this.fileList);
        this.dialogVisible = false;
        console.log( this.editSpu.carouselImages);
      },
    }
}
</script>

<style>

</style>